const bcrypt = require('bcrypt')
const Users = require('../../models/users')

const updateUser = async (req, res) => {
  try {
    const existingUser = await Users.findOne({email: req.body.email})
    if (!existingUser) {
      return res.status(403).json({success: false, msg: 'User not found'})
    }
    const {id, ...user} = req.body
    user.password = await bcrypt.hash(user.password, 10)
    const updatedUser = await Users.findOneAndUpdate({id: id}, {$set: user}, {new: true})
    updatedUser
      ? res.status(200).json(updatedUser)
      : res.status(404).json({success: false, msg: 'Пользователь не найден'})
  } catch (err) {
    return res.status(500).json({success: false, msg: err.message})
  }
}
module.exports = {
  updateUser,
}
